#!/usr/bin/env bash

{

nvm_detect_profile() {
  if [ "${PROFILE-}" = '/dev/null' ]; then
    # the user has specifically requested NOT to have nvm touch their profile
    return
  fi

  if [ -n "${PROFILE}" ] && [ -f "${PROFILE}" ]; then
    echo "${PROFILE}"
    return
  fi

  local DETECTED_PROFILE
  DETECTED_PROFILE=''

  if [ "${SHELL#*bash}" != "$SHELL" ]; then
    if [ -f "$HOME/.bashrc" ]; then
      DETECTED_PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
      DETECTED_PROFILE="$HOME/.bash_profile"
    fi
  elif [ "${SHELL#*zsh}" != "$SHELL" ]; then
    if [ -f "${ZDOTDIR:-${HOME}}/.zshrc" ]; then
      DETECTED_PROFILE="${ZDOTDIR:-${HOME}}/.zshrc"
    elif [ -f "${ZDOTDIR:-${HOME}}/.zprofile" ]; then
      DETECTED_PROFILE="${ZDOTDIR:-${HOME}}/.zprofile"
    fi
  fi

  if [ -z "$DETECTED_PROFILE" ]; then
    for EACH_PROFILE in ".profile" ".bashrc" ".bash_profile" ".zprofile" ".zshrc"
    do
      if DETECTED_PROFILE="$(nvm_try_profile "${ZDOTDIR:-${HOME}}/${EACH_PROFILE}")"; then
        break
      fi
    done
  fi

  if [ -n "$DETECTED_PROFILE" ]; then
    echo "$DETECTED_PROFILE"
  fi
}


echo "=> Deleting nvm source directory"
rm -rf $HOME/.nvm


echo "=> Removing nvm related environment variables"
profile_file=$(nvm_detect_profile)
sed -i$(uname -s | grep -q Darwin && echo " ''" || echo "") '/export NVM_DIR="*"/d' ${profile_file}
sed -i$(uname -s | grep -q Darwin && echo " ''" || echo "") '/\[ -s "\$NVM_DIR\/nvm.sh" \]/d' ${profile_file}
sed -i$(uname -s | grep -q Darwin && echo " ''" || echo "") '/\[ -s "\$NVM_DIR\/bash_completion" \]/d' ${profile_file}


echo "=> Uninstallation Complete"
echo -e "=> Manually check environment variables in \n${profile_file}"

}
